import { request } from 'umi';

export async function query() {
  return request<API.UserInfo[]>('/api/users');
}

export async function currentUser() {
  return request<API.UserInfo>('/api/restricted/currentUser');
}

export async function login(logp: API.LoginParams) {
  const data = new FormData();
  data.append('username', logp.username);
  data.append('password', logp.password);
  return request(`/api/login`, {
    method: 'POST',
    body: data,
  });
}

/** 保存token */
export const saveToken = (token: string) => {
  localStorage.removeItem('unloadTime');
  localStorage.setItem('Authorization', 'Bearer ' + token);
};

/** 获取token */
export const getToken = () => {
  return localStorage.getItem('Authorization');
  // const loadTime = new Date().getTime();
  // const unloadTime_str = localStorage.getItem('unloadTime');
  // const unloadTime = unloadTime_str ? Number(unloadTime_str) : 0;
  // const gap = unloadTime === 0 ? 0 : loadTime - unloadTime;
  // if (gap > 2000) {
  //   return null;
  // } else {
  //   return localStorage.getItem('Authorization');
  // }
};

/** 删除token */
export const removeToken = () => {
  localStorage.removeItem('Authorization');
};

export async function changePassword(oldPassword: string, newPassword: string) {
  const data = new FormData();
  data.append('OldPassword', oldPassword);
  data.append('NewPassword', newPassword);
  return request(`/api/restricted/Menu/Password`, {
    method: 'POST',
    body: data,
  });
}
export async function initPassword(userIDs: number[]) {
  const data = new FormData();
  data.append('UserIDs', JSON.stringify(userIDs));
  return request(`/api/restricted/Menu/InitPassword`, {
    method: 'POST',
    body: data,
  });
}

export async function leaveOffice(userIDs: number[]) {
  const data = new FormData();
  data.append('UserIDs', JSON.stringify(userIDs));
  return request(`/api/restricted/Menu/LeaveOffice`, {
    method: 'POST',
    body: data,
  });
}

export async function initPasswordAll() {
  return request(`/api/restricted/Menu/InitPasswordAll`);
}
